package com.demon.net.converter

import com.demon.net.AppResponse
import com.google.gson.Gson
import com.google.gson.TypeAdapter
import com.google.gson.reflect.TypeToken
import okhttp3.ResponseBody
import org.json.JSONObject
import retrofit2.Converter
import java.io.IOException
import java.lang.reflect.Type


class CustomResponseConverter<T> internal constructor(
  private val gson: Gson,
  private val adapter: TypeAdapter<out Any>,
  private val mType: Type
) : Converter<ResponseBody, T> {
  @Throws(IOException::class) override fun convert(value: ResponseBody): T {
    val response: AppResponse<*> = AppResponse<Any?>()
    return try {
      val body = value.string()
      val json = JSONObject(body)
      val body1 = json.optString("data")
      val msgJson = json.optString("msg")
      val ret = json.optInt("code")
//      val ret = msgJson.optInt("code")
//      val msg = msgJson.optString("info", "")
      if (ret == AppResponse.CODE_SUCCESS) {
        gson.fromJson(body, mType)
      } else {
        val responseMessage = msgJson
        response.msg = responseMessage.toString()
        response.code = ret
        response as T
      }
    } catch (e: Exception) {
      throw RuntimeException(e.message)
    } finally {
      value.close()
    }
  }
}